﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Asessment.aspx.cs" Inherits="CRMWeb.Pages.Asessment" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <script type="text/javascript">
        var formHasChanged = false;
        $(document).ready(function () {
            $('#lastresult').combobox({
                onLoadSuccess: function () {
                    $('#lastresult').combobox('textbox').bind('click', function () {
                        $('#lastresult').combobox('showPanel');
                    });
                }
            });

            $('#ContentPlaceHolder1_appProfile_hdnAssessment').val('true');
            window.onbeforeunload = function (e) {

                //Account Number:
                var lnNum = $("#txtLNumber").val();
                var hdnlnNum = $("#hdnAccNo").val();

                if (lnNum == hdnlnNum) {
                    formHasChanged = false;
                }
                else {
                    formHasChanged = true;
                }

                if (formHasChanged) {
                    var message = "You have not saved your changes.", e = e || window.event;
                    if (e) {
                        e.returnValue = message;
                    }
                    return message;
                }

                var lnLender = $("#txtLender").val();
                var hdnlnLender = $("#hdnLen").val();

                if (lnLender == hdnlnLender) {
                    formHasChanged = false;
                }
                else {
                    formHasChanged = true;
                }

                if (formHasChanged) {
                    var message = "You have not saved your changes.", e = e || window.event;
                    if (e) {
                        e.returnValue = message;
                    }
                    return message;
                }

                var lndate = $('#cmdlastAssessedDate').datebox('getValue', new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear());
                var hdnlndate = $("#hdnAsmentDate").val();

                if (lndate == hdnlndate) {
                    formHasChanged = false;
                }
                else {
                    formHasChanged = true;
                }

                if (formHasChanged) {
                    var message = "You have not saved your changes.", e = e || window.event;
                    if (e) {
                        e.returnValue = message;
                    }
                    return message;
                }

                var lnMemoNote = $("#txtMemoNote").val();
                var hdnlnMemoNote = $("#hdnMemoNote").val();
                if (lnMemoNote == hdnlnMemoNote) {
                    formHasChanged = false;
                }
                else {
                    formHasChanged = true;
                }

                if (formHasChanged) {
                    var message = "You have not saved your changes.", e = e || window.event;
                    if (e) {
                        e.returnValue = message;
                    }
                    return message;
                }
            }
        });
    </script>

    <div style="float: left; width: 100%">
        <input type="hidden" id="hdnloanid" />
        <input type="hidden" id="hdnbankid1" />
        <input type="hidden" id="hdnbankid2" />
        <table style="width: 100%;">
            <tr>
                <td style="vertical-align: top; width: 100%;">
                    <div id="divMsg"></div>
                    <div class="topform_section">
                        <div class="firstform_section">
                            <div id="divLoanTitle" class="ftitle">CREATE LOAN</div>
                            <div class="fitem">
                                <label>Last Result:</label>
                                <input class="easyui-combobox" id="lastresult" style="width: 240px;"
                                    data-options="url:'/WebServices/AM/LoanForm.ashx?method=GetAssessmentLastResults',
				                                    valueField:'AssessmentLastResult',
				                                    textField:'AssessmentLastResult',
				                                    panelHeight:'auto'" />
                                <input type="hidden" id="hdnLastRes" runat="server" />
                            </div>
                            <div class="fitem">
                                <label>Last Assessed Date:</label>
                               
                              <%--  <input id="cmdlastAssessedDate" name="cmdlastAssessedDate" class="easyui-datebox" data-options="formatter:formatLoanDate" style="width: 90px;" />--%>
                                 <input id="cmdlastAssessedDate" name="cmdlastAssessedDate" class="easyui-datebox" data-options="formatter:au_formatter,parser:au_parser" style="width: 90px;" />
                                <input type="hidden" id="hdnAsmentDate" runat="server" />
                            </div>
                            <div class="fitem">
                                <label>Account No:</label>
                                <input id="txtLNumber" style="width: 150px;" class="easyui-validatebox" name="LoanNumber" />
                                <input type="hidden" id="hdnAccNo" runat="server" />
                            </div>
                            <div class="fitem">
                                <label>Lender:</label>
                                <input id="txtLender" style="width: 150px;" class="easyui-validatebox" name="LenderName" />
                                <input type="hidden" id="hdnLen" runat="server" />
                            </div>
                        </div>
                        <div class="firstform_section">
                            <div class="fitem" style="padding-left: 20px; padding-top: 20px;">
                                <label>Note:</label>
                                <textarea id="txtMemoNote" name="txtMemoNote" style="width: 79%; height: 123px;"></textarea>
                                <input type="hidden" id="hdnMemoNote" runat="server" />

                            </div>
                        </div>
                        <div class="firstform_section">
                            <div class="fitem" style="text-align: right;">
                                <%-- <span id="lnkbtnSaveLoan"><a href="javascript:void(0)" id="lnkSaveLoanData" class="easyui-linkbutton" data-options="iconCls:'icon-save'" onclick="SaveLoan()">Save</a></span>
                                <span id="lnkbtnAddLoan"><a href="javascript:void(0)" class="easyui-linkbutton"   data-options="iconCls:'icon-add',disabled:true" onclick="AddLoan()">Create Loan</a></span>
                                <span id="lnkbtnLoan"><a id="abtnLoan" href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" onclick="btnLoanProfile()">Loan</a></span>--%>
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
        </table>
    </div>

    <script type="text/javascript">

        //Check the lenderStatus value and invoke the function:

        function CheckLenderStatus(app_id) {
            $.ajax({
                type: "get",
                data: { app_id: app_id },
                url: "/WebServices/AM/LoanForm.ashx?method=CheckLenderStatus",
                success: function (data) {
                    if (data == "[]") {
                     //   alert("new");
                        AddLoan();
                    }
                    else {
                        $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                         //   alert("edit");
                            SaveLoans();
                        });
                    }
                },
                error: function (data) {
                    //alert('Error');
                }
            });
        }

        $(document).ready(function () {
            LoanProfile();
            DisplayLoan();
            setHeight();
        });

        $(document).keydown(function (event) {
            if ((event.which == 83 || event.which == 115) && (event.ctrlKey || event.metaKey) || (event.which == 19)) {
                event.preventDefault();
                CheckLenderStatus(getQuerystring('app_id', ''));
                return false;
            }
            return true;
        });

        /*Add New Loan*/
        function AddLoan() {
            var loanid;
            /*Get Text Value*/
            var LNumber = $("#txtLNumber").val();
            var lender = $("#txtLender").val();
            var Memo = $("#txtMemoNote").val();
            //var todaydate = CurrentDate();
            var CreateDate = $('#cmdlastAssessedDate').datebox('getValue');
            if (CreateDate != '')
              //  CreateDate = DefaultformatLoanDate($('#cmdlastAssessedDate').datebox('getValue'));
                CreateDate = DefaultformatLoanDate($('#cmdlastAssessedDate').datebox('getValue'));

            var LoanStatus = 1;
            var LastResult = $('#lastresult').combobox('getValue');
            var LoanAmount = 0;
            var LowerRate = 0;
            var HigherRate = 0;
            var DishonourFee = 0;
            var DefaultNotice = 0;

            //insert record into loan table
            $.ajax({
                url: '/WebServices/AM/LoanForm.ashx?method=AddLoanInfoFromAsessment',
                contentType: 'application/json; charset=utf-8',
                data: { 'app_id': getQuerystring('app_id', ''), 'LoanNumber': LNumber, 'Lender': lender, 'CreateDate': CreateDate, 'EditDate': CreateDate, 'LoanStatus': LoanStatus, 'LastResult': LastResult, 'Memo': Memo },
                success: function (data) {
                    loanid = data;
                    //insert record into bank details table for Transfer Of Funds
                    $.ajax({
                        url: '/WebServices/AM/LoanForm.ashx?method=AddBankInfoFromAsessment',
                        contentType: 'application/json; charset=utf-8',
                        data: { "LoanID": loanid, "LoanType": "DDR BANK ACCOUNT SETUP" },
                        success: function (data) {
                            if (data == '1') {
                                var Description = '';
                                Description = "<span style='color:black;font-weight: bold'>" + "Loan created ApplicationId: " + getQuerystring('app_id', '') + "</span>" + "<br/>";
                                var dateVal = $('#cmdlastAssessedDate').datebox('getValue', new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear());

                                if ($("#hdnAsmentDate").val() != dateVal)
                                    Description += "Last Assessed Date " + "from " + "<span style='color:green'>" + $("#hdnAsmentDate").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + dateVal + "</span>" + "," + "<br/>";

                                if ($("#hdnLastRes").val() != LastResult)
                                    Description += "Last Result " + "from " + "<span style='color:green'>" + $("#hdnLastRes").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + LastResult + "</span>" + "," + "<br/>";

                                if ($("#hdnAccNo").val() != $("#txtLNumber").val())
                                    Description += "Account No " + "from " + "<span style='color:green'>" + $("#hdnAccNo").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + $("#txtLNumber").val() + "</span>" + "," + "<br/>";

                                if ($("#hdnLen").val() != $("#txtLender").val())
                                    Description += "Lender " + "from " + "<span style='color:green'>" + $("#hdnLen").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + $("#txtLender").val() + "</span>" + "," + "<br/>";

                                if ($("#hdnMemoNote").val() != $("#txtMemoNote").val())
                                    Description += "Note " + "from " + "<span style='color:green'>" + $("#hdnMemoNote").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + $("#txtMemoNote").val() + "</span>" + "," + "<br/>";

                                //To update history table:
                                saveHistory(Description);
                               // $.messager.alert('Morgan CRM', 'Insert Data Successfully');

                                $('#abtnLoan').linkbutton('enable');
                                DisplayLoan();
                            }
                        }
                    });
                }
            });
        }

        function DefaultformatLoanDate(value) {
            dArr = value.split('/');
            return dArr[1] + '/' + dArr[0] + '/' + dArr[2];
        }

        function formatLoanDate(value, row) {
            if (value == null)
                return value;
            var date = new Date(value);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            var d = date.getDate();
            return (d < 10 ? ('0' + d) : d) + '/' + (m < 10 ? ('0' + m) : m) + '/' + y;
        }

        //Australia date format dd/mm/yyyy --From Wade
        function AuDefaultformatLoanDate(value) {
            dArr = value.split('/');
            return dArr[0] + '/' + dArr[1] + '/' + dArr[2];
        }

        function au_formatter(value, row) {
            var date = (value === null) ? new Date() : new Date(value);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            var d = date.getDate();
            return (d < 10 ? ('0' + d) : d) + '/' + (m < 10 ? ('0' + m) : m) + '/' + y;
        }

        function au_parser(s) {
            if (!s) return new Date();

            var ss = (s.split('/'));
            var d = new Number(ss[0]);
            var m = new Number(ss[1]);
            var y = new Number(ss[2]);

            if (!isNaN(d) && !isNaN(m) && !isNaN(y)) {
                return new Date(y, m - 1, d);
            }
            else {
                return new Date();
            }
        }
        //End  --20131023  

        /*Update Loan*/
        function SaveLoan() {
            /*Get Text Value*/

            var LNumber = $("#txtLNumber").val();
            var lender = $("#txtLender").val();
            var LastResult = $('#lastresult').combobox('getValue');
            var EditDate = $('#cmdlastAssessedDate').datebox('getValue');
            if (EditDate != '')
             //   EditDate = DefaultformatLoanDate($('#cmdlastAssessedDate').datebox('getValue'));
                EditDate = DefaultformatLoanDate($('#cmdlastAssessedDate').datebox('getValue'));

            var todaydate = CurrentDate();
            var Memo = $("#txtMemoNote").val();
            //insert record into loan table
            $.ajax({
                url: '/WebServices/AM/LoanForm.ashx?method=UpdateLoanInfoFromAsessment',
                contentType: 'application/json; charset=utf-8',
                data: { 'app_id': getQuerystring('app_id', ''), 'LoanNumber': LNumber, 'Lender': lender, 'EditDate': EditDate, 'LastResult': LastResult, 'Memo': Memo },
                success: function (data) {
                    if (data == 1) {
                        var Description = '';
                        Description = "<span style='color:black;font-weight: bold'>" + "ApplicationId: " + getQuerystring('app_id', '') + "</span>" + "<br/>";
                        var dateVal = $('#cmdlastAssessedDate').datebox('getValue', new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear());

                        if ($("#hdnAsmentDate").val() != dateVal)
                            Description += "Last Assessed Date " + "from " + "<span style='color:green'>" + $("#hdnAsmentDate").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + dateVal + "</span>" + "," + "<br/>";

                        if ($("#hdnLastRes").val() != LastResult)
                            Description += "Last Result " + "from " + "<span style='color:green'>" + $("#hdnLastRes").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + LastResult + "</span>" + "," + "<br/>";

                        if ($("#hdnAccNo").val() != $("#txtLNumber").val())
                            Description += "Account No " + "from " + "<span style='color:green'>" + $("#hdnAccNo").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + $("#txtLNumber").val() + "</span>" + "," + "<br/>";

                        if ($("#hdnLen").val() != $("#txtLender").val())
                            Description += "Lender " + "from " + "<span style='color:green'>" + $("#hdnLen").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + $("#txtLender").val() + "</span>" + "," + "<br/>";

                        if ($("#hdnMemoNote").val() != $("#txtMemoNote").val())
                            Description += "Note " + "from " + "<span style='color:green'>" + $("#hdnMemoNote").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + $("#txtMemoNote").val() + "</span>" + "," + "<br/>";

                        saveHistory(Description);
                        DisplayLoan();
                    }
                }
            });
        }
        function CurrentDate() {
            var currentDate = new Date()
            return currentDate.getMonth() + 1 + "/" + currentDate.getDate() + "/" + currentDate.getFullYear();
        }

        function saveHistory(desc) {
            var HistoryDate = CurrentDate();
            var currentTime = new Date()
            var hours = currentTime.getHours()
            var minutes = currentTime.getMinutes()
            var seconds = currentTime.getSeconds();
            var HistoryTime = hours + ':' + minutes + ':' + seconds;

            var Action = 'Field changed(System)';
            var Operator = $('#ContentPlaceHolder1_appProfile_hdnUserName').val();
            var app_id = getQuerystring("app_id", null);

            $.ajax({
                type: "Post",
                data: { HistoryType: 'Application', contactid: '0', hdate: HistoryDate, htime: HistoryTime, action: Action, user: Operator, description: desc, appid: app_id },
                url: "/WebServices/History.ashx?method=saveNewHistory",
                success: function (result) {
                    //$('#dgApplicationHistory').datagrid('reload');
                    //var tab = $('#MainTab').tabs('getTab', 'Verification Checklist'); // get selected panel
                    //tab.panel('refresh', '/Pages/Application/VerificationChecklist.aspx?app_id=' + app_id);
                }
            });
        }

        /*Update Loan For Ctrl+s*/
        function SaveLoans() {
            /*Get Text Value*/

            var LNumber = $("#txtLNumber").val();
            var lender = $("#txtLender").val();
            var LastResult = $('#lastresult').combobox('getValue');

            var todaydate = CurrentDate();
            var Memo = $("#txtMemoNote").val();
            //insert record into loan table
            $.ajax({
                url: '/WebServices/AM/LoanForm.ashx?method=UpdateLoanInfoFromAsessment',
                contentType: 'application/json; charset=utf-8',
                data: { 'app_id': getQuerystring('app_id', ''), 'LoanNumber': LNumber, 'Lender': lender, 'EditDate': todaydate, 'LastResult': LastResult, 'Memo': Memo },
                success: function (data) {
                    if (data == 1) {
                        var Description = '';
                        Description = "<span style='color:black;font-weight: bold'>" + "ApplicationId: " + getQuerystring('app_id', '') + "</span>" + "<br/>";
                        var dateVal = $('#cmdlastAssessedDate').datebox('getValue', new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear());

                        if ($("#hdnAsmentDate").val() != dateVal)
                            Description += "Last Assessed Date " + "from " + "<span style='color:green'>" + $("#hdnAsmentDate").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + dateVal + "</span>" + "," + "<br/>";

                        if ($("#hdnLastRes").val() != LastResult)
                            Description += "Last Result " + "from " + "<span style='color:green'>" + $("#hdnLastRes").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + LastResult + "</span>" + "," + "<br/>";

                        if ($("#hdnAccNo").val() != $("#txtLNumber").val())
                            Description += "Account No " + "from " + "<span style='color:green'>" + $("#hdnAccNo").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + $("#txtLNumber").val() + "</span>" + "," + "<br/>";

                        if ($("#hdnLen").val() != $("#txtLender").val())
                            Description += "Lender " + "from " + "<span style='color:green'>" + $("#hdnLen").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + $("#txtLender").val() + "</span>" + "," + "<br/>";

                        if ($("#hdnMemoNote").val() != $("#txtMemoNote").val())
                            Description += "Note " + "from " + "<span style='color:green'>" + $("#hdnMemoNote").val() + "</span>" + " " + "change to " + "<span style='color:red'>" + $("#txtMemoNote").val() + "</span>" + "," + "<br/>";

                        saveHistory(Description);
                        DisplayLoan();
                    }
                }
            });
        }

        /*Display Loan */
        function DisplayLoan() {
            $.ajax({
                url: '/WebServices/AM/LoanForm.ashx?method=SearchLoanDetailByAppID',
                contentType: 'application/json; charset=utf-8',
                data: { 'app_id': getQuerystring('app_id', '') },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        /* set value in labels */
                        $('#hdnloanid').val(rec.LoanID);
                        if (rec.LoanID != null)
                            $('#divLoanTitle').html("UPDATE LOAN");
                        $('#txtLNumber').val(rec.LoanNumber);
                        $('#hdnAccNo').val(rec.LoanNumber);
                        $('#txtLender').val(rec.Lender);
                        $('#hdnLen').val(rec.Lender);
                        $("#txtMemoNote").val(rec.Memo);
                        $("#hdnMemoNote").val(rec.Memo);
                        //$('#cmdlastAssessedDate').datebox('setValue', new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear());
                     //   $('#cmdlastAssessedDate').datebox('setValue', formatLoanDate(rec.EditDate));
                        $('#cmdlastAssessedDate').datebox('setValue', au_formatter(rec.EditDate,null));

                        $('#hdnAsmentDate').val(formatLoanDate(rec.EditDate));
                        $('#lastresult').combobox('setValue', rec.LastResult);
                        $("#hdnLastRes").val(rec.LastResult);
                        if (rec.EffectiveDate != null && rec.DoubleChecked == '1') {
                            $('#lnkSaveLoanData').linkbutton('disable');
                        }
                        $('#lnkbtnSaveLoan').show();
                        $('#lnkbtnAddLoan').hide();
                    });
                }
            });
        }

        function LoanProfile() {
            $.ajax({
                url: '/WebServices/AM/LoanForm.ashx?method=SearchLoanDetailByAppID',
                contentType: 'application/json; charset=utf-8',
                data: { 'app_id': getQuerystring('app_id', '') },
                success: function (data) {
                    if (data != "[]") {
                        $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                            if (rec.LoanID == null) {
                                $('#cmdlastAssessedDate').datebox('setValue', new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear());
                                $('#hdnAsmentDate').val(new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear());
                                $('#abtnLoan').linkbutton('disable');
                            }
                        });
                    }
                    else {
                        $('#cmdlastAssessedDate').datebox('setValue', new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear());
                        $('#hdnAsmentDate').val(new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear());
                        $('#abtnLoan').linkbutton('disable');
                    }
                }
            });
        }

        function btnLoanProfile() {
            $.ajax({
                url: '/WebServices/AM/LoanForm.ashx?method=SearchLoanDetailByAppID',
                contentType: 'application/json; charset=utf-8',
                data: { 'app_id': getQuerystring('app_id', '') },
                success: function (data) {
                    if (data != "[]") {
                        $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                            if (rec.LoanID != null) {
                                window.location.href = "/Pages/AM/LoanSelectionMenu.aspx?LoanID=" + rec.LoanID;
                            }
                            else {
                                $('#abtnLoan').linkbutton('disable');
                            }
                        });
                    }
                    else {
                        $('#abtnLoan').linkbutton('disable');
                    }
                }
            });
        }

    </script>
</body>
</html>
